package com.bsoft.exchange.service;

import com.alibaba.fastjson.JSONObject;
import com.bsoft.exchange.dao.his.*;
import com.bsoft.exchange.domain.*;
import com.bsoft.exchange.pojo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;


@Service
public class PushService {

	@Autowired
	HcicXxtsZyyyMapper hcicXxtsZyyyMapper;

	@Autowired
	HcicXxtsCyjsMapper hcicXxtsCyjsMapper;

	@Autowired
	HcicXxtsPdjhMapper hcicXxtsPdjhMapper;

	@Autowired
	HcicXxtsQryyMapper hcicXxtsQryyMapper;

	@Autowired
	HcicXxtsSmxxMapper hcicXxtsSmxxMapper;

	@Autowired
	HcicXxtsYyghMapper hcicXxtsYyghMapper;

	@Autowired
	HcicXxtsZjzfMapper hcicXxtsZjzfMapper;


	@Autowired
	RestTemplate restTemplate;

	@Value("${push.base-url}")
	private String baseurl;

	@Value("${push.name-QueueInfo}")
	private String queueInfo;

	@Value("${push.name-CanceledWorks}")
	private String canceledWorks;

	@Value("${push.name-PayTradeNot}")
	private String payTradeNot;

	@Value("${push.name-OpenProveNot}")
	private String openProveNot;

	@Value("${push.name-DischargeSettlementNot}")
	private String dischargeSettlementNot;

	@Value("${push.name-OperaStatus}")
	private String operaStatus;

	@Value("${push.name-ConfirmNot}")
	private String confirmNot;


	public void pushOpenProveNot() {
		
		//1、获取需要推送数据

		List<HcicXxtsZyyyDomain> msgList = hcicXxtsZyyyMapper.getOpenProveNotList();
		String url = baseurl + openProveNot;
		Long megId;
		//2、组织数据推送
		for(HcicXxtsZyyyDomain msg : msgList){

			/*Map<String, Object> requestParam = new HashMap<>();
			requestParam.put("organizationId",msg.getOrganizationid());
			requestParam.put("organizationName",msg.getOrganizationname());
			requestParam.put("doctorId",msg.getDoctorid());
			requestParam.put("doctorName",msg.getDoctorname());
			requestParam.put("proveDate",msg.getProvedate());
			requestParam.put("cardType",msg.getCardtype());
			requestParam.put("cardNumber",msg.getCardnumber());*/

			PushOpenProveNotPojo pojo = new PushOpenProveNotPojo();
			pojo.setOrganizationId(msg.getOrganizationid());
			pojo.setDoctorId(msg.getDoctorid());
			pojo.setDoctorName(msg.getDoctorname());
			pojo.setProveDate(msg.getProvedate());
			pojo.setCardType(msg.getCardtype());
			pojo.setCardNumber(msg.getCardnumber());
			pojo.setOrganizationName(msg.getOrganizationname());
			//pojo.setPatientId(msg.getPatientid());

			String body = pushMessage(url,pojo);

			pushBusinessData("openProveNot",msg.getMsgid(),body);

		}
		System.out.println("推送住院证开出通知");
		
	}
    @Transactional(value="hisTransactionManager",rollbackFor = Exception.class)
    public void pushBusinessData(String BusinessType,Long msgid,String body) {

		if(BusinessType == null || "".equals(BusinessType)){
			return ;
		}

		//不区分大小写，先转换成大写
		BusinessType = BusinessType.toUpperCase();

		Long pushStatus = 0L;
		String pushMsg ="成功";

		//解析返回的body
		JSONObject json = JSONObject.parseObject(body);
		if(json.get("code")!=null && "200".equals(json.get("code"))){
			pushStatus = 1L;
			if(json.get("message") != null){
				pushMsg = json.get("message").toString();
			}
		}else{
			pushStatus = 0L;
			if(json.get("message") != null){
				pushMsg = json.get("message").toString();
			}
		}

		//截取下pushMsg
		int max=1980;
		int len= getAsciiWordLen2(pushMsg);
		if (len > max) {
			pushMsg = getAsciiLenWord(pushMsg, max);
		}
		//json.getString("name");
		//JDK1.8支持String
		switch (BusinessType) {
			case "OPENPROVENOT":

				//转移历史表
				hcicXxtsZyyyMapper.saveOpenProveNotHistory(msgid,pushStatus,pushMsg);
				//删除原表
				hcicXxtsZyyyMapper.deleteByPrimaryKey(msgid);

				break;
			case "CANCELEDWORKS":

				hcicXxtsYyghMapper.saveCanceledWorksHistory(msgid,pushStatus,pushMsg);
				hcicXxtsYyghMapper.deleteByPrimaryKey(msgid);

				break;
			case "OPERASTATUS":

				hcicXxtsSmxxMapper.saveOperaStatusHistory(msgid,pushStatus,pushMsg);
				hcicXxtsSmxxMapper.deleteByPrimaryKey(msgid);

				break;
			case "QUEUEINFO":

				hcicXxtsPdjhMapper.saveQueueInfoHistory(msgid,pushStatus,pushMsg);
				hcicXxtsPdjhMapper.deleteByPrimaryKey(msgid);

				break;
			case "CONFIRMNOT":
				hcicXxtsQryyMapper.saveConfirmNotHistory(msgid,pushStatus,pushMsg);
				hcicXxtsQryyMapper.deleteByPrimaryKey(msgid);
				break;
			case "PAYTRADENOT":
				hcicXxtsZjzfMapper.savePayTradeNotHistory(msgid,pushStatus,pushMsg);
				hcicXxtsZjzfMapper.deleteByPrimaryKey(msgid);
				break;
			case "DISCHARGESETTLEMENTNOT":
				hcicXxtsCyjsMapper.saveDischargeSettlementNotHistory(msgid,pushStatus,pushMsg);
				hcicXxtsCyjsMapper.deleteByPrimaryKey(msgid);
				break;
			default:
				break;
		}

        return;

    }

	private String pushMessage(String url,Object requestParam){

		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON_UTF8);

		//HttpEntity<Map<String, Object>> request = new HttpEntity<Map<String, Object>>(requestParam, headers);
		HttpEntity<Object> request = new HttpEntity<Object>(requestParam, headers);

		ResponseEntity<String> entity = restTemplate.postForEntity(url, request, String.class);

		String body = entity.getBody();

		return body;
	}

	public void pushCanceledWorks() {

		//1、获取需要推送数据

		List<HcicXxtsYyghDomain> msgList = hcicXxtsYyghMapper.getCanceledWorksList();
		String url = baseurl + canceledWorks;

		/*PushCanceledWorksPojo pojo = new PushCanceledWorksPojo();
		List<PushCanceledWorksDataPojo> listSchedule = new ArrayList<>();
		PushCanceledWorksDataPojo dataPojo = new PushCanceledWorksDataPojo();*/

		//2、组织数据推送
		for(HcicXxtsYyghDomain msg : msgList){

			PushCanceledWorksPojo pojo = new PushCanceledWorksPojo();

			pojo.setOrganizationId(msg.getOrganizationid());
			pojo.setOutpatientType(msg.getOutpatienttype());

			List<PushCanceledWorksDataPojo> listSchedule = new ArrayList<>();
			PushCanceledWorksDataPojo dataPojo = new PushCanceledWorksDataPojo();

			dataPojo.setDepartmentId(msg.getDepartmentid());
			dataPojo.setDoctorId(msg.getDoctorid());
			dataPojo.setScheduleDate(msg.getScheduledate());
			dataPojo.setPeriodId(msg.getPeriodid());

			listSchedule.add(dataPojo);
			pojo.setListSchedule(listSchedule);

			String body = pushMessage(url,pojo);

			pushBusinessData("canceledWorks",msg.getMsgid(),body);
		}

		/*for(HcicXxtsYyghDomain msg : msgList){

			if(!organizationId.equals(msg.getOrganizationid()) || outpatientType != msg.getOutpatienttype()){

				//非第一次
				if( i > 0){

					String body = pushMessage(url,pojo);
					pushBusinessData("canceledWorks",msg.getMsgid());
				}
				i ++;
				pojo = new PushCanceledWorksPojo();
				listSchedule = new ArrayList<>();

				pojo.setOrganizationId(msg.getOrganizationid());
				pojo.setOutpatientType(msg.getOutpatienttype());

			}

			dataPojo = new PushCanceledWorksDataPojo();
			dataPojo.setDepartmentId(msg.getDepartmentid());
			dataPojo.setDoctorId(msg.getDoctorid());
			dataPojo.setScheduleDate(msg.getScheduledate());
			dataPojo.setPeriodId(msg.getPeriodid());

			listSchedule.add(dataPojo);
			pojo.setListSchedule(listSchedule);

			organizationId = msg.getOrganizationid();
			outpatientType = msg.getOutpatienttype();

		}

		String body = pushMessage(url,pojo);
		pushBusinessData("canceledWorks",msg.getMsgid());*/

		System.out.println("推送停诊通知");
		
	}
	
	public void pushDischargeSettlementNot() {
		//1、获取需要推送数据

		List<HcicXxtsCyjsDomain> msgList = hcicXxtsCyjsMapper.getDischargeSettlementNotList();
		String url = baseurl + dischargeSettlementNot;

		//2、组织数据推送
		for(HcicXxtsCyjsDomain msg : msgList){

			PushDischargeSettlementNotPojo pojo = new PushDischargeSettlementNotPojo();
			pojo.setOrganizationId(msg.getOrganizationid());
			pojo.setPatientId(msg.getPatientid());
			pojo.setDoctorId(msg.getDoctorid());
			pojo.setDoctorName(msg.getDoctorname());
			pojo.setCardType(msg.getCardtype());
			pojo.setCardNumber(msg.getCardnumber());
			pojo.setOrganizationName(msg.getOrganizationname());

			String body = pushMessage(url,pojo);

			pushBusinessData("dischargeSettlementNot",msg.getMsgid(),body);
		}
		System.out.println("推送出院通知");
		
	}
	
	public void pushOperaStatus() {

		//1、获取需要推送数据

		List<HcicXxtsSmxxDomain> msgList = hcicXxtsSmxxMapper.getOperaStatusList();
		String url = baseurl + operaStatus;

		//2、组织数据推送
		for(HcicXxtsSmxxDomain msg : msgList){

			PushOperaStatusPojo pojo = new PushOperaStatusPojo();
			pojo.setOrganizationId(msg.getOrganizationid());
			pojo.setOrganizationName(msg.getOrganizationname());
			pojo.setOperationId(msg.getOperationid());
			pojo.setPatientId(msg.getPatientid());
			pojo.setCardType(msg.getCardtype());
			pojo.setCardNumber(msg.getCardnumber());
			pojo.setOperationCode(msg.getOperationcode());
			pojo.setOperationName(msg.getOperationname());
			pojo.setDepartmentCode(msg.getDepartmentcode());
			pojo.setDepartmentName(msg.getDepartmentname());
			pojo.setStatus(msg.getStatus());
			pojo.setStatusStr(msg.getStatusstr());

			String body = pushMessage(url,pojo);

			pushBusinessData("operaStatus",msg.getMsgid(),body);
		}

		System.out.println("推送手术状态通知");
		
	}
	
	public void pushQueueInfo() {

		//1、获取需要推送数据
		List<HcicXxtsPdjhDomain> msgList = hcicXxtsPdjhMapper.getQueueInfoList();
		String url = baseurl + queueInfo;

		//2、组织数据推送
		for(HcicXxtsPdjhDomain msg : msgList){

			PushQueueInfoPojo pojo = new PushQueueInfoPojo();
			pojo.setOrganizationId(msg.getOrganizationid());
			pojo.setQueuesId(msg.getQueuesid());

			String body = pushMessage(url,pojo);

			pushBusinessData("queueInfo",msg.getMsgid(),body);
		}

		System.out.println("推送排队信息通知");
		
	}
	
	public void pushConfirmNot() {

		//1、获取需要推送数据
		List<HcicXxtsQryyDomain> msgList = hcicXxtsQryyMapper.getConfirmNotList();
		String url = baseurl + confirmNot;

		//2、组织数据推送
		for(HcicXxtsQryyDomain msg : msgList){

			PushConfirmNotPojo pojo = new PushConfirmNotPojo();

			pojo.setOrganizationId(msg.getOrganizationid());
			//pojo.setPatientId(msg.getPatientid());
			pojo.setCardType(msg.getCardtype());
			pojo.setCardNumber(msg.getCardnumber());
			//pojo.setWardType(msg.getWardtype());
			pojo.setWardType(String.format("%02d", Integer.parseInt(msg.getWardtype())));

			pojo.setHospitalProveCode(msg.getHospitalprovecode());
			pojo.setDepartmentName(msg.getDepartmentname());
			pojo.setAppointmentDate(msg.getAppointmentdate());


			String body = pushMessage(url,pojo);

			pushBusinessData("confirmNot",msg.getMsgid(),body);
		}
		System.out.println("推送确认住院预约通知");
		
	}
	
	public void pushPayTradeNot() {

		//1、获取需要推送数据
		List<HcicXxtsZjzfDomain> msgList = hcicXxtsZjzfMapper.getPayTradeNotList();
		String url = baseurl + payTradeNot;

		//2、组织数据推送
		for(HcicXxtsZjzfDomain msg : msgList){

			PushPayTradeNotPojo pojo = new PushPayTradeNotPojo();
			pojo.setOrganizationId(msg.getOrganizationid());
			pojo.setPatientName(msg.getPatientname());
			pojo.setCardType(msg.getCardtype());
			pojo.setCardNumber(msg.getCardnumber());
			pojo.setDoctorId(msg.getDoctorid());
			pojo.setDoctorName(msg.getDoctorname());
			pojo.setDepartmentId(msg.getDepartmentid());
			pojo.setDepartmentName(msg.getDepartmentname());
			pojo.setTotalFee(msg.getTotalfee());
			pojo.setFeeInformation(msg.getFeeinformation());
			pojo.setDiagnosisDate(msg.getDiagnosisdate());
			pojo.setOrganizationName(msg.getOrganizationname());

			String body = pushMessage(url,pojo);

			pushBusinessData("payTradeNot",msg.getMsgid(),body);
		}

		System.out.println("推送诊间支付提醒通知");
		
	}


	public static int getAsciiWordLen2(String s)
	{
		s = s.replaceAll("[^\\x00-\\xff]", "**");
		int length = s.length();
		return length;
	}
	/*根据长度截图字符串
	 * Ascii格式 汉字 两个长度 英文一个长度的的字节计算
	 * * add by lct 2017-10-16*/
	public static String getAsciiLenWord(String s,int len)
	{
		String ss="";
		StringBuffer stringBuffer = new StringBuffer();
		int length = 0;
		for(int i = 0; i < s.length(); i++)
		{
			int ascii = Character.codePointAt(s, i);
			if(ascii >= 0 && ascii <=255) {
				length++;
			} else {
				length += 2;
			}

			if (length>len){
				break;
			}
			else{
				String sub= s.substring(i,i+1);
				stringBuffer.append(sub);
			}

		}
		ss=stringBuffer.toString();
		return ss;

	}
}
